package repository

import (
	"github.com/lab-online/internal/class/entity"
	"github.com/lab-online/internal/class/infra/model"
	"gorm.io/gorm"
)

// SaveClass 若未指定 ID 则新增，否则更新非零字段
func (r *Repository) SaveClass(classEntity entity.ClassEntity) (entity.ClassEntity, error) {
	class := model.New(model.WithEntity(classEntity))
	var err error
	if class.ID == 0 {
		err = r.db.Create(class).Error
	} else {
		err = r.db.Model(class).Updates(class).Error
	}

	if err != nil {
		return nil, errorHandler(err)
	}
	return class.ToEntity(), nil
}

// SaveWithStudents 保存班级及学生 需要 id
func (r *Repository) SaveWithStudents(classEntity entity.ClassEntity) (entity.ClassEntity, error) {
	class := model.New(model.WithEntity(classEntity))
	db := r.db.Session(&gorm.Session{FullSaveAssociations: true})
	if err := db.Unscoped().
		Model(class).Association("Students").
		Unscoped().Replace(class.Students); err != nil {
		return nil, errorHandler(err)
	}

	return class.ToEntity(), nil
}
